package cn.pet.service.manage.auth;


import cn.pet.service.manage.auth.entity.LoginVO;
import cn.pet.service.manage.context.GlobalContext;
import cn.pet.service.manage.entity.PetUser;
import cn.pet.service.manage.service.PetUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collection;

public class MyAuthenticationProvider implements AuthenticationProvider {

    final PasswordEncoder passwordEncoder;

    final JWTUtil jwtUtil;

    final PetUserService petUserService;

    public MyAuthenticationProvider(PasswordEncoder passwordEncoder, JWTUtil jwtUtil, PetUserService petUserService) {
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
        this.petUserService = petUserService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = String.valueOf(authentication.getName());
        String password = String.valueOf(authentication.getCredentials());
        return authenticate(username, password);
    }

    public Authentication authenticate(String username, String password) {
        if (username == null || username.length() < 1) {
            throw new UsernameNotFoundException("用户名不可以为空!");
        }
        if (password == null || password.length() < 1) {
            throw new BadCredentialsException("密码不可以为空!");
        }

        LambdaQueryWrapper<PetUser> petUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        petUserLambdaQueryWrapper.eq(PetUser::getUsername,username);

        PetUser petUser = petUserService.getOne(petUserLambdaQueryWrapper);

        if (petUser == null) {
            throw new BadCredentialsException("无效用户名或密码!");
        }

        if (!passwordEncoder.matches(password, petUser.getPassword())) {
            throw new BadCredentialsException("无效用户名与密码!");
        }


//        String token = (String) redisUtil.hget("USER_TOKEN", String.valueOf(user.getId()));
//        if (token != null && jwtUtil.isTokenExpired(token)) {
//            token = jwtUtil.createToken(user.getId());
//        } else {
//            token = jwtUtil.createToken(user.getId());
//        }

//        QueryWrapper<DUser> query = new QueryWrapper<>();
//        query.eq("username", username);
//        DUser user = userService.getOne(query, false);
//        if (user == null) {
//            throw new BadCredentialsException("无效用户名或密码!");
//        }
//
//        if (!passwordEncoder.matches(password, user.getPassword())) {
//            throw new BadCredentialsException("无效用户名与密码!");
//        }
//
//        String token = (String) redisUtil.hget("USER_TOKEN", String.valueOf(user.getId()));
//        if (token != null && jwtUtil.isTokenExpired(token)) {
//            token = jwtUtil.createToken(user.getId());
//            redisUtil.hset("USER_TOKEN", String.valueOf(user.getId()), token, 86400);
//        } else {
//            token = jwtUtil.createToken(user.getId());
//            redisUtil.hset("USER_TOKEN", String.valueOf(user.getId()), token, 86400);
//        }
//
//        Collection<? extends GrantedAuthority> authorities = getUserAuthorities(user.getId());
        String token = GlobalContext.get(petUser.getId());
        if (token != null && jwtUtil.isTokenExpired(token)) {
            token = jwtUtil.createToken(petUser.getId());
            GlobalContext.add(petUser.getId(),token);
        } else {
            token = jwtUtil.createToken(petUser.getId());
            GlobalContext.add(petUser.getId(),token);
        }
        Collection<? extends GrantedAuthority> authorities = null;
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(getUserInfo(petUser.getId()), token, authorities);

        return usernamePasswordAuthenticationToken;
    }
//
//    public Collection<? extends GrantedAuthority> getUserAuthorities(Serializable userId) {
//        QueryWrapper<DRoleUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId);
//        List<DRoleUser> roleUserList = roleUserService.list(queryWrapper);
//        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        if (roleUserList != null && roleUserList.size() > 0) {
//            List<Integer> roleIds = new ArrayList<>(roleUserList.size());
//            for (DRoleUser roleUser : roleUserList) {
//                roleIds.add(roleUser.getRoleId());
//            }
//
//            QueryWrapper<DRole> roleQueryWrapper = new QueryWrapper<>();
//            roleQueryWrapper.in("id", roleIds);
//
//            List<DRole> roleList = roleService.list(roleQueryWrapper);
//            if (roleList != null && roleList.size() > 0) {
//                for (DRole role : roleList) {
//                    String roleName = role.getCode();
//                    if(roleName==null || roleName.length()<1){
//                        roleName = role.getName();
//                        if(roleName==null || roleName.length()<1){
//                            continue;
//                        }
//                    }
//                    grantedAuthorities.add(new SimpleGrantedAuthority(roleName));
//                }
//            }
//        }
//        return grantedAuthorities;
//    }
//
//    public UserPermission getUserPermission(Integer userId) {
//        return roleService.getUserPermission(userId);
//    }

    public PetUser getUserInfo(Integer userId){
        PetUser user = petUserService.getById(userId);
        user.setPassword(null);
        return user;
    }


    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }
}
